package com.cse.bpass;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Scanner;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Vibrator;
import android.speech.tts.TextToSpeech;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;

public class PasscodeView extends View implements TextToSpeech.OnInitListener, TextToSpeech.OnUtteranceCompletedListener{
	String TAG = "DRAWING";
	
	private int dX;
	private int dY;
	private int x1;
	private int x2;
	private int y1;
	private int y2;
	private int type;
	
	private String storedPass;
	private FileWriter fw;
	private Vibrator vibrator;
	
	private boolean start;
	private Context context;
	
	protected TextToSpeech tts;
	
	Paint p;
	ArrayList<Draw> drawing;
	
	public PasscodeView(Context context, int width, int height, int type, Vibrator vr,
				TextToSpeech tts) {
		super(context);
		this.context = context;
		
		start = false;
		
		//Create TextToSpeech
		this.tts = tts;
		
		p = new Paint();
		p.setColor(Color.WHITE);
		p.setStrokeWidth(10);
		p.setAntiAlias(true);
		drawing = new ArrayList<Draw>();
		
		dX = width / 5 * 2;
		dY = height / 5;
		x1 = dX;
		x2 = width - dX;
		y1 = dY;
		y2 = height - dY;
		vibrator = vr;
		this.type = type;
		
		getPass(this.type);

	}
	
	@Override
	public boolean onTouchEvent(MotionEvent event){
		switch(event.getActionMasked()){
		case MotionEvent.ACTION_DOWN:
			if(start){
				drawing.add(new Draw(event.getX(), event.getY(), false));
				start=true;
				break;
			}
		case MotionEvent.ACTION_MOVE:
			if(start){
				drawing.add(new Draw(event.getX(), event.getY(), true));
				readPass(event);
				start=true;
				break;
			}
			
		case MotionEvent.ACTION_UP:
			drawing.clear();
			break;
			
		case MotionEvent.ACTION_POINTER_UP:
			if(!start){
				tts.speak("Passcode has started",
						TextToSpeech.QUEUE_FLUSH, null);
				start = true;
			}else{
				Log.d("type", type + "");
				if(password.equals("")){
					tts.speak("Empty passcode, please try again", TextToSpeech.QUEUE_FLUSH, null);
					return false;
				}
				if(type == 0){
					try{
						fw = new FileWriter("/sdcard/password.txt");
						fw.write(password);
						Log.d("password", password + " -0");
						tts.speak("New passcode is created, please confirm it", 
								TextToSpeech.QUEUE_FLUSH, null);
						fw.close();
						type = 3;
						drawing.clear();
						start = false;
						getPass(type);
					}catch (IOException e) {
						e.printStackTrace();
					}		
				}else if(type == 1 || type == 2 || type == 3){
					drawing.clear();
					if(!password.equals("") && checkPass(password)){
						Log.d("password", "true");
						
						if(type == 1){
							tts.speak("Passcode is solved, back to phone main menu",
									TextToSpeech.QUEUE_FLUSH, null);
							Intent toMain = new Intent(Intent.ACTION_MAIN);
							toMain.addCategory(Intent.CATEGORY_HOME);
							toMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
							tts.shutdown();
							((Activity)getContext()).startActivity(toMain);
							
						}else if(type == 2){
							String longSpeech ="Passcode solved. Create new passcode" +
									"and confirm it";
							tts.speak(longSpeech, TextToSpeech.QUEUE_FLUSH, null);
							start = false;
							type = 0;
							drawing.clear();
						}else{
							Log.d("password", password + " -0");
					        tts.setOnUtteranceCompletedListener(this);
							HashMap<String, String> hashUtter = new HashMap<String, String>();
							hashUtter.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, "completed");
							tts.speak("Passcode is confirmed, back to B pass main menu",
									TextToSpeech.QUEUE_FLUSH, hashUtter);
						}
					}else{
						if(type==2||type==1){
							tts.speak("Incorrect passcode, please try again",
									TextToSpeech.QUEUE_FLUSH, null);
						}
						if(type==3){
							Log.d("psfdasf", password + "12");
							type = 0;
							tts.speak("Confirm failed, please recreate your passcode and" +
									"confirm again", TextToSpeech.QUEUE_FLUSH, null);
						}
						
						start = false;
						drawing.clear();
					}
					Log.d("password", password + " -1");
				}
				currentBox = "";
				newBox = "";
				password = "";
			}		
		}
		
		invalidate();
		return true;
	}
	
	@Override
	protected void onDraw(Canvas canvas){
		super.onDraw(canvas);
		
		canvas.drawColor(Color.BLACK);
		
		for(int i = 1; i < drawing.size(); i++){
			if(drawing.get(i).draw){
				canvas.drawLine(drawing.get(i-1).x, drawing.get(i-1).y, 
						drawing.get(i).x, drawing.get(i).y, p);
				
			}else{
				canvas.drawPoint(drawing.get(i).x, drawing.get(i).y, p);
			}
		}
	}
	
	private String currentBox = "";
	private String newBox = "";
	private String password = "";
	
	public void readPass(MotionEvent event){
		float xCor = event.getX();
		float yCor = event.getY();
		
		if (event.getAction() == MotionEvent.ACTION_UP){
			if (checkPass(password))
					//open();
			password = "";
		}
		
		if (xCor <= x1){
			if (yCor <= y1){
				vibrator.vibrate(100);
				newBox = "1";
			}else if (yCor >= y2){
				vibrator.vibrate(100);
				newBox = "3";	
			}
		}else if (xCor >= x2){
			if (yCor <= y1){
				vibrator.vibrate(100);
				newBox = "2";
			}else if (yCor >=y2){
				vibrator.vibrate(100);
				newBox = "4";
			}
		}
		
		if (!currentBox.equals(newBox)){
			password += newBox;
			currentBox = newBox;
		}		
	}
	
	public boolean checkPass(String password){
		Log.d("password", password);
		return password.equals(storedPass);
	}
	
	private class Draw{
		float x;
		float y;
		boolean draw;
		
		public Draw(float x, float y, boolean draw){
			this.x = x;
			this.y = y;
			this.draw = draw;
		}
	}

	public void getPass(int type){
		if(type == 1 || type == 2 || type == 3){
			Scanner console;
			FileReader fr;
			try {
				fr = new FileReader("/sdcard/password.txt");
				console = new Scanner(fr);
				storedPass = "";
				if(console.hasNext()){
					storedPass = console.nextLine();
					Log.d("Read Password", storedPass);
				}
			} catch (FileNotFoundException e1) {
				e1.printStackTrace();
			}
		}
	}
	
	public void onInit(int arg0) {
		String longSpeech = "Find the corner to begin with by using one finger. Once you find the starting corner," +
				"start by tapping the screen with your second finger while your first finger remains on the screen";
		tts.speak(longSpeech, TextToSpeech.QUEUE_ADD, null);
	}

	public void onUtteranceCompleted(String utteranceId) {
		if(utteranceId.equals("completed")){
			Log.d("Enter", "Enter");
			Intent toMenu = new Intent();
			toMenu.setClass(context, BPassActivity.class);
			((Activity)getContext()).startActivity(toMenu);
		}
		
	}
}
